package com.module_live.view;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.lib.fastkit.db.shared_prefrences.SharedPreferenceManager;
import com.lib.fastkit.utils.file.FileUtils;
import com.lib.fastkit.utils.log.LogUtil;
import com.lib.fastkit.utils.px_dp.DisplayUtil;
import com.lib.fastkit.utils.share.tool.StringUtil;
import com.lib.fastkit.views.dialog.http.DialogUtils;
import com.lib.utls.upload.QiNiuUploadTask;
import com.lib.utls.upload.initerface.FileUploadListener;
import com.luck.picture.lib.tools.ToastManage;
import com.module_live.R;
import com.module_live.bean.UploadVoice;
import com.zyyoona7.popup.EasyPopup;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TeacherDealRecordPopup {


    private Activity activity;

    public View parentView;

    DialogUtils dialogUtils;

    public TeacherDealRecordPopup(Activity activity) {

        this.activity = activity;

        initPopuPopu();
    }

    private EasyPopup popu;


    private void initPopuPopu() {
        popu = EasyPopup.create()
                .setContext(activity)
                .setContentView(R.layout.popup_study_teacher_dealrecord)
                .setWidth(WindowManager.LayoutParams.FILL_PARENT)
                .setHeight(WindowManager.LayoutParams.FILL_PARENT)
                .setOnViewListener(new EasyPopup.OnViewListener() {
                    @Override
                    public void initViews(View view, EasyPopup basePopup) {

                        dialogUtils = new DialogUtils();

                        initView(view);

                        initRecodVoiceUtils();

                    }

                })
                .setFocusAndOutsideEnable(true)
                .apply();

    }

    public LinearLayout linVoice;
    public TextView tvStart, tvFinish;
    public ImageView ivDealImg;

    private void initView(View view) {

        linVoice = view.findViewById(R.id.lin_voice);

        tvStart = view.findViewById(R.id.tv_start);
        tvFinish = view.findViewById(R.id.tv_finish);

        ivDealImg = view.findViewById(R.id.iv_dealimg);

        tvStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (uploadVoiceList != null) {
                    if (uploadVoiceList.size() > 2) {

                        ToastManage.s(activity, "单次最多录入3条语音哦！");
                    } else {
                        recordVoicePopupUtils.showVoicePopu(parentView);
                    }
                }
            }
        });

        tvFinish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (uploadVoiceList.size() == 0) {
                    dismiss();
                } else {
                    if (listener != null) {
                        listener.onTeacherRecordData(uploadVoiceList);
                    }
                    dismiss();
                }
            }
        });

    }

    public void updateDealImgAndView(String imgLoaclPath, View rooView) {

        if (StringUtil.isNotEmpty(imgLoaclPath, true)) {

            LogUtil.e("处理之后，图片的本地地址为：" + imgLoaclPath);

//            ivDealImg.setImageURI(Uri.fromFile(new File(imgLoaclPath)));

//            Bitmap bitmap = BitmapFactory.decodeStream(getClass().getResourceAsStream(imgLoaclPath));
//            ivDealImg.setImageBitmap(bitmap);

//            Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver()
//                    .openInputStream(imgeUri));
//            imageview.setImageBitmap(bitmap);

            ivDealImg.setImageBitmap(getLoacalBitmap(imgLoaclPath));

        }

        this.parentView = rooView;

        if (uploadVoiceList != null && uploadVoiceList.size() > 0) {
            uploadVoiceList.clear();
        }
    }


    /**
     * 加载本地图片
     *
     * @param url
     * @return
     */
    public static Bitmap getLoacalBitmap(String url) {
        try {
            FileInputStream fis = new FileInputStream(url);
            return BitmapFactory.decodeStream(fis);  ///把流转化为Bitmap图片

        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }


    public void dismiss() {
        popu.dismiss();
    }


    public void showAnswerPopuPopu(View view) {
        popu.showAtLocation(view, Gravity.CENTER, 0, 0);

    }

    interface TeacherDealedRecordListener {

        void onTeacherRecordData(List<UploadVoice> uploadVoiceList);
    }

    public TeacherDealedRecordListener listener;

    public void setTeacherDealedRecordListener(TeacherDealedRecordListener recordListener) {

        this.listener = recordListener;
    }


    private RecordVoicePopupUtils recordVoicePopupUtils;

    private void initRecodVoiceUtils() {
        recordVoicePopupUtils = new RecordVoicePopupUtils(activity);

        recordVoicePopupUtils.setRecordVoicePopupUtilsListener(new RecordVoicePopupUtils.RecordVoicePopupUtilsListener() {
            @Override
            public void onVoiceIconClick() {

            }

            @Override
            public void onRecordFinish(Uri audioPath, int duration) {

                finishRecordDo(audioPath, duration);
            }
        });
    }


    private List<UploadVoice> uploadVoiceList = new ArrayList<>();

    private void finishRecordDo(Uri audioPath, int duration) {
        String realPath = FileUtils.getRealFilePath(activity, audioPath);

        final UploadVoice uploadVoice = new UploadVoice();

        uploadVoice.setDuration(duration);
        uploadVoice.setPath(realPath);
        /**
         * 插入音频UI
         */
        final CommonSoundItemView commonSoundItemView = new CommonSoundItemView(activity);
        commonSoundItemView.setAudioEntity(uploadVoice);
        commonSoundItemView.setCommonSoundItemViewListener(new CommonSoundItemView.CommonSoundItemViewListener() {
            @Override
            public void onDelete(UploadVoice audioEntity) {
                linVoice.removeView(commonSoundItemView);

                LogUtil.e("移除voice：" + audioEntity.getPath());
                UploadVoice voice = null;
                for (int i = 0; i < uploadVoiceList.size(); i++) {
                    if (audioEntity.getPath().equals(uploadVoiceList.get(i).getPath())) {
                        voice = uploadVoiceList.get(i);
                    }
                }
                if (voice != null) {
                    uploadVoiceList.remove(voice);
                }
                initVoiceUI();
            }

        });

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        params.gravity = Gravity.CENTER;
        params.topMargin = DisplayUtil.dip2px(activity, 16);
        commonSoundItemView.setLayoutParams(params);

        linVoice.addView(commonSoundItemView);
        uploadVoice.setView(commonSoundItemView);

        uploadFile(realPath, uploadVoice);
    }

    /**
     * 刷新音频布局
     */
    private void initVoiceUI() {
        LogUtil.e("Map大小:" + uploadVoiceList.size());

    }


    private void uploadFile(final String compressPath, final UploadVoice uploadVoice) {

        LogUtil.e("上传文件路径" + compressPath);

        dialogUtils.showNormalDialog(activity, "语音正在上传中......");

        QiNiuUploadTask qiNiuUploadTask = new QiNiuUploadTask(activity);
        qiNiuUploadTask.setFileUploadListener(new FileUploadListener() {
            @Override
            public void onProgress(int progress) {

            }

            @Override
            public void onSuccess(final String s) {

                dialogUtils.dismiss();
                if (null == s || null == s || "null".equals(s) || s.length() < 5) {

                    ToastManage.s(activity, "语音上传失败，请重新录入!");

                } else {

                    uploadVoice.setUrl(s);
                    uploadVoice.setPlayUrl(SharedPreferenceManager.getInstance(activity).getUserCache().getQiNiuUrl() + s);

                    uploadVoiceList.add(uploadVoice);

                    initVoiceUI();

                    LogUtil.e("上传语音成功:" + s);

                }

            }

            @Override
            public void onError(String e) {

                dialogUtils.dismiss();

                LogUtil.e("文件上传失败:" + e);
                initVoiceUI();
                ToastManage.s(activity, "录制语音失败！");


            }
        });

        qiNiuUploadTask.execute(compressPath, SharedPreferenceManager.getInstance(activity).getUserCache().getQiNiuToken());

    }

}
